<template>
  <layout 
    tabbar="none" 
    navbar="none" 
    :showBack="true" 
    class="dark-theme"
    navbarBackgroundColor="#020303"
    :showTabbarProp="false"
  >
    <view class="chat-page">
      <!-- 自定义顶部导航栏 -->
      <view class="header" :style="{paddingTop: vuex_status_bar_height + 'px'}">
        <view class="header-left">
          <view class="back-btn" @tap="goBack">
            <text class="tn-icon-left"></text>
          </view>
        </view>
        <view class="header-title">
          <view class="user-info">
            <view class="username">{{ targetUser.nickname || '用户' }}</view>
            <view class="online-status" v-if="targetUser.isOnline">在线</view>
          </view>
        </view>
        <view class="header-actions">
          <view class="icon-btn" @tap="showUserInfo">
            <text class="tn-icon-more-circle"></text>
          </view>
        </view>
      </view>
      
      <!-- 聊天内容区域 -->
      <z-paging 
        ref="chatPaging" 
        v-model="messageList" 
        @query="loadMessages"
        :default-page-size="15"
        :auto="true"
        :refresher-enabled="true"
        :use-chat-record-mode="true"
        :show-scrollbar="false"
        :paging-style="{
          height: `calc(100vh - ${inputBarHeight + vuex_status_bar_height + 44}px)`,
          paddingTop: `${vuex_status_bar_height + 44}px`
        }"
        :bg-color="'#020303'"
        :empty-view-text="'开始聊天吧'"
      >
        <!-- 聊天消息列表 -->
        <view class="chat-container">
          <block v-for="(item, index) in messageList" :key="index">
            <!-- 系统消息 -->
            <view class="message system" v-if="item.type === 'system'">
              <view class="message-content">
                <text>{{ item.content }}</text>
              </view>
            </view>
            
            <!-- 日期分隔 -->
            <view class="message system" v-if="item.type === 'date'">
              <view class="message-content">
                <text>{{ item.content }}</text>
              </view>
            </view>
            
            <!-- 亲密度提升 -->
            <view class="message system" v-if="item.type === 'intimacy'">
              <view class="message-content message-intimacy">
                <view class="intimacy-icon">
                  <text class="tn-icon-like-fill"></text>
                </view>
                <text>{{ item.content }}</text>
              </view>
            </view>
            
            <!-- 普通消息 -->
            <view class="message" 
              v-if="item.type === 'text' || item.type === 'image' || item.type === 'voice' || item.type === 'gift'" 
              :class="[item.senderId === userId ? 'sent' : 'received']"
            >
              <!-- 头像 -->
              <view class="message-avatar" @tap="viewUserProfile(item.senderId)">
                <image 
                  :src="item.senderId === userId ? userAvatar : targetUser.avatar || 'https://picsum.photos/seed/avatar/100'" 
                  mode="aspectFill"
                />
              </view>
              
              <!-- 消息内容 -->
              <view class="message-content">
                <!-- 文本消息 -->
                <view class="message-text" v-if="item.type === 'text'">
                  {{ item.content }}
                </view>
                
                <!-- 图片消息 -->
                <view class="message-image" v-if="item.type === 'image'" @tap="previewImage(item.content)">
                  <image :src="item.content" mode="widthFix" />
                </view>
                
                <!-- 语音消息 -->
                <view 
                  class="message-voice" 
                  v-if="item.type === 'voice'"
                  :class="{ 'playing': currentPlayingVoice === index }"
                  @tap="playVoice(item.content, index)"
                >
                  <view class="voice-icon">
                    <text class="tn-icon-voice"></text>
                  </view>
                  <view class="voice-wave">
                    <view class="wave-bar" v-for="i in 5" :key="i"></view>
                  </view>
                  <view class="voice-duration">
                    {{ item.duration || '0"' }}
                  </view>
                </view>
                
                <!-- 礼物消息 -->
                <view class="message-gift" v-if="item.type === 'gift'">
                  <view class="gift-content">
                    <view class="gift-title">{{ item.senderId === userId ? '你送出礼物' : '收到礼物' }}</view>
                    <view class="gift-detail">
                      <view class="gift-left">
                        <image 
                          class="gift-thumbnail" 
                          :src="parseGiftContent(item.content).giftImage" 
                          mode="aspectFit"
                        />
                      </view>
                      <view class="gift-right">
                        <view class="gift-name">{{ parseGiftContent(item.content).giftName }}</view>
                        <view class="gift-quantity">x{{ parseGiftContent(item.content).quantity }}</view>
                      </view>
                    </view>
                  </view>
                </view>
                
                <!-- 消息时间 -->
                <view class="message-time">
                  {{ formatTime(item.timestamp) }}
                </view>
              </view>
              
              <!-- 消息状态 -->
              <view class="message-status" v-if="item.senderId === userId">
                <text class="tn-icon-loading status-sending" v-if="item.status === 'sending'"></text>
                <text class="tn-icon-check status-sent" v-else-if="item.status === 'sent'"></text>
                <text class="tn-icon-check-fill status-delivered" v-else-if="item.status === 'delivered'"></text>
                <text class="tn-icon-check-double status-read" v-else-if="item.status === 'read'"></text>
                <text class="tn-icon-close status-failed" v-else-if="item.status === 'failed'"></text>
              </view>
            </view>
          </block>
        </view>
      </z-paging>
      
      <!-- 输入工具栏 -->
      <view class="input-bar" :style="{bottom: keyboardHeight + 'px'}">
        <view class="input-container">
          <view class="input-box" :class="{ 'input-box-focused': isInputFocused }">
            <textarea
              v-model="messageText"
              class="message-input"
              :adjust-position="false"
              :cursor-spacing="12"
              :show-confirm-bar="false"
              :hold-keyboard="true"
              :maxlength="-1"
              placeholder="发送消息..."
              @focus="onInputFocus"
              @blur="onInputBlur"
              @confirm="sendTextMessage"
              @input="adjustTextareaHeight"
              :style="{height: textareaHeight + 'px'}"
            />
          </view>
          <view class="input-actions">
            <view class="action-btn emoji-btn" :class="{ 'active': showEmojiPanel }" @tap="toggleEmojiPanel">
              <text class="tn-icon-emoji"></text>
            </view>
            <view class="action-btn more-btn" :class="{ 'active': showToolPanel }" @tap="toggleToolPanel">
              <text class="tn-icon-add"></text>
            </view>
            <view class="send-btn" @tap="sendTextMessage" v-if="messageText.trim()">
              <text>发送</text>
            </view>
            <view class="action-btn voice-btn" :class="{ 'active': showVoicePanel }" @tap="toggleVoiceInput" v-else>
              <text class="tn-icon-voice"></text>
            </view>
          </view>
        </view>
        
        <!-- 语音输入面板 -->
        <view class="voice-panel" v-if="showVoicePanel">
          <view class="voice-button" 
            :class="{ 'recording': isRecording }"
            @touchstart="startRecording" 
            @touchend="stopRecording"
            @touchcancel="cancelRecording"
          >
            <text>{{ isRecording ? '松开发送' : '按住说话' }}</text>
            <view class="recording-waves" v-if="isRecording">
              <view class="wave-circle" v-for="i in 3" :key="i"></view>
            </view>
          </view>
          <view class="recording-tip" v-if="isRecording">
            <text>上滑取消发送</text>
          </view>
        </view>
        
        <!-- 工具面板 -->
        <view class="tool-panel" v-if="showToolPanel">
          <view class="tool-grid">
            <view class="tool-item" @tap="chooseImage('album')">
              <view class="tool-icon">
                <text class="tn-icon-image"></text>
              </view>
              <view class="tool-name">相册</view>
            </view>
            <view class="tool-item" @tap="chooseImage('camera')">
              <view class="tool-icon">
                <text class="tn-icon-camera"></text>
              </view>
              <view class="tool-name">拍照</view>
            </view>
            <view class="tool-item" @tap="chooseLocation">
              <view class="tool-icon">
                <text class="tn-icon-location"></text>
              </view>
              <view class="tool-name">位置</view>
            </view>
            <view class="tool-item" @tap="sendGift">
              <view class="tool-icon">
                <text class="tn-icon-present"></text>
              </view>
              <view class="tool-name">礼物</view>
            </view>
            <view class="tool-item" @tap="sendFile">
              <view class="tool-icon">
                <text class="tn-icon-file"></text>
              </view>
              <view class="tool-name">文件</view>
            </view>
            <view class="tool-item" @tap="openVideoCall">
              <view class="tool-icon">
                <text class="tn-icon-video"></text>
              </view>
              <view class="tool-name">视频通话</view>
            </view>
            <view class="tool-item" @tap="openVoiceCall">
              <view class="tool-icon">
                <text class="tn-icon-phone"></text>
              </view>
              <view class="tool-name">语音通话</view>
            </view>
            <view class="tool-item" @tap="shareContact">
              <view class="tool-icon">
                <text class="tn-icon-addressbook"></text>
              </view>
              <view class="tool-name">分享名片</view>
            </view>
          </view>
        </view>
        
        <!-- 表情面板 -->
        <view class="emoji-panel" v-if="showEmojiPanel">
          <view class="emoji-tabs">
            <scroll-view scroll-x class="emoji-tabs-scroll">
              <view class="emoji-tab" 
                v-for="(tab, index) in emojiTabs" :key="index"
                :class="{ 'active': activeEmojiTab === index }"
                @tap="activeEmojiTab = index"
              >
                {{ tab.name }}
              </view>
            </scroll-view>
            <view class="emoji-delete" @tap="deleteEmoji">
              <text class="tn-icon-delete"></text>
            </view>
          </view>
          
          <swiper class="emoji-content" :current="activeEmojiTab" @change="onEmojiSwiperChange">
            <swiper-item v-for="(tab, tabIndex) in emojiTabs" :key="tabIndex">
              <scroll-view scroll-y class="emoji-list">
                <view class="emoji-grid">
                  <view 
                    class="emoji-item" 
                    v-for="(emoji, emojiIndex) in tab.emojis" 
                    :key="emojiIndex"
                    @tap="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </view>
                </view>
              </scroll-view>
            </swiper-item>
          </swiper>
          
          <view class="emoji-footer">
            <view class="emoji-send-btn" @tap="sendTextMessage" v-if="messageText.trim()">
              <text>发送</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 礼物弹窗 -->
      <view class="gift-modal" v-if="showGiftModal" @tap.stop="closeGiftModal">
        <view class="gift-modal-content" @tap.stop>
          <view class="gift-modal-header">
            <view class="gift-modal-title">赠送礼物</view>
            <view class="gift-modal-close" @tap="closeGiftModal">
              <text class="tn-icon-close"></text>
            </view>
          </view>
          
          <view class="gift-modal-user-info">
            <view class="gift-modal-balance">
              <text>余额：</text>
              <text class="balance-amount">{{ userBalance }} <text class="tn-icon-money"></text></text>
            </view>
            <view class="recharge-btn" @tap="rechargeBalance">充值</view>
          </view>
          
          <view class="gift-categories">
            <scroll-view scroll-x class="gift-category-scroll">
              <view 
                class="gift-category-btn" 
                v-for="(category, index) in giftCategories" 
                :key="index"
                :class="{ 'active': currentGiftCategory === category.id }"
                @tap="changeGiftCategory(category.id)"
              >
                {{ category.name }}
              </view>
            </scroll-view>
          </view>
          
          <view class="gift-grid-container">
            <scroll-view scroll-y class="gift-grid">
              <view class="gift-grid-items">
                <view 
                  class="gift-item" 
                  v-for="(gift, index) in filteredGifts" 
                  :key="index"
                  :class="{'selected': selectedGift && selectedGift.id === gift.id}"
                  @tap="selectGiftItem(gift)"
                >
                  <image class="gift-image" :src="gift.image" mode="aspectFit"></image>
                  <view class="gift-name">{{ gift.name }}</view>
                  <view class="gift-price">{{ gift.price }} <text class="tn-icon-money"></text></view>
                </view>
              </view>
            </scroll-view>
          </view>
          
          <view class="gift-footer" v-if="selectedGift">
            <view class="gift-quantity">
              <view class="quantity-label">数量：</view>
              <view class="quantity-controls">
                <view class="quantity-btn" @tap="decreaseQuantity">
                  <text class="tn-icon-minus"></text>
                </view>
                <view class="quantity-value">{{ giftQuantity }}</view>
                <view class="quantity-btn" @tap="increaseQuantity">
                  <text class="tn-icon-add"></text>
                </view>
              </view>
            </view>
            <view class="total-price">总价：{{ calculateTotalPrice() }} <text class="tn-icon-money"></text></view>
            <view class="send-gift-btn" @tap="sendSelectedGift">
              <text>赠送</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 亲密度升级弹窗 -->
      <view class="intimacy-levelup" v-if="showLevelUpModal" @tap="closeIntimacyLevelUpModal">
        <view class="levelup-content" @tap.stop>
          <view class="levelup-icon">
            <text class="tn-icon-favorite"></text>
          </view>
          <view class="levelup-title">亲密度等级提升！</view>
          <view class="levelup-desc">
            恭喜你们的关系更进一步，现在是 Lv.{{ intimacyLevel }} 级了
            <view class="levelup-progress">
              距离下一级还需: {{ maxIntimacyValue - (intimacyValue % maxIntimacyValue) }} 亲密度
            </view>
          </view>
          <view class="levelup-btn" @tap="closeIntimacyLevelUpModal">太棒了</view>
        </view>
      </view>
    </view>
  </layout>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'ChatPage',
  data() {
    return {
      // 聊天对象信息
      targetUser: {
        id: '',
        nickname: '',
        avatar: '',
        isOnline: false
      },
      
      // 消息列表
      messageList: [],
      
      // 输入相关状态
      messageText: '',
      textareaHeight: 20,
      keyboardHeight: 0,
      inputBarHeight: 50,
      isInputFocused: false,
      
      // 面板显示控制
      showEmojiPanel: false,
      showToolPanel: false,
      showVoicePanel: false,
      isRecording: false,
      recordingTime: 0,
      recordingTimer: null,
      
      // 语音播放控制
      currentPlayingVoice: -1,
      
      // 表情面板配置
      activeEmojiTab: 0,
      emojiTabs: [
        {
          name: '表情',
          emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', 
                  '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', 
                  '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', 
                  '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟']
        },
        {
          name: '手势',
          emojis: ['👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '🤙', '👈', 
                  '👉', '👆', '👇', '☝️', '✊', '🤛', '🤜', '👊', '🤚', 
                  '👋', '🤝', '👏', '🙌', '👐', '🤲', '🙏', '💪', '🦾', 
                  '🦵', '🦿', '🦶', '👂', '🦻', '👃', '🧠', '👣', '🫀']
        },
        {
          name: '热门',
          emojis: ['❤️', '🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '🤍', 
                  '💯', '💢', '💥', '💫', '💦', '💨', '🕳️', '💣', '💬', 
                  '👁️‍🗨️', '🗨️', '🗯️', '💭', '💤', '👋', '🎮', '🎯', 
                  '🏆', '🏅', '🥇', '🥈', '🥉', '🎖️', '🏵️', '🎗️', '🎪', '🎭']
        },
        {
          name: '游戏',
          emojis: ['🎮', '🕹️', '🎲', '🎯', '🎳', '🎪', '🎭', '🎨', '🧩', 
                  '♟️', '🎴', '🃏', '🀄', '🎴', '🎪', '🎬', '🎤', '🎧', 
                  '🎼', '🎹', '🥁', '🎷', '🎺', '🎸', '🎻', '🥇', '🥈', 
                  '🥉', '🏆', '🏅', '🎖', '🎗', '🏵', '🎫', '🎟️', '🎪']
        }
      ],

      // 语音相关
      recorderManager: null,
      innerAudioContext: null,
      
      // 礼物相关
      showGiftModal: false, // 是否显示礼物弹窗
      selectedGift: null, // 选中的礼物
      giftQuantity: 1, // 礼物数量
      currentGiftCategory: 'all', // 当前选中的礼物分类
      userBalance: 1000, // 用户余额
      
      // 亲密度相关
      intimacyValue: 120, // 当前亲密度值
      intimacyLevel: 1, // 当前亲密度等级
      maxIntimacyValue: 100, // 每级所需亲密度值
      showLevelUpModal: false, // 是否显示等级提升弹窗
      
      // 礼物分类
      giftCategories: [
        { id: 'all', name: '全部' },
        { id: 'popular', name: '热门' },
        { id: 'love', name: '爱情' },
        { id: 'funny', name: '搞笑' },
        { id: 'luxury', name: '豪华' },
        { id: 'game', name: '游戏' }
      ],
      
      // 礼物列表
      giftList: [
        { id: 1, name: '爱心', price: '10', image: 'https://cdn-icons-png.flaticon.com/128/1029/1029132.png', category: 'love' },
        { id: 2, name: '玫瑰', price: '50', image: 'https://cdn-icons-png.flaticon.com/128/1192/1192232.png', category: 'love' },
        { id: 3, name: '蛋糕', price: '30', image: 'https://cdn-icons-png.flaticon.com/128/1684/1684041.png', category: 'love' },
        { id: 4, name: '钻戒', price: '500', image: 'https://cdn-icons-png.flaticon.com/128/1030/1030270.png', category: 'luxury' },
        { id: 5, name: '皇冠', price: '300', image: 'https://cdn-icons-png.flaticon.com/128/1205/1205776.png', category: 'luxury' },
        { id: 6, name: '小丑', price: '40', image: 'https://cdn-icons-png.flaticon.com/128/1809/1809756.png', category: 'funny' },
        { id: 7, name: '气球', price: '20', image: 'https://cdn-icons-png.flaticon.com/128/2749/2749678.png', category: 'funny' },
        { id: 8, name: '游戏机', price: '80', image: 'https://cdn-icons-png.flaticon.com/128/686/686589.png', category: 'game' },
        { id: 9, name: '火箭', price: '1000', image: 'https://cdn-icons-png.flaticon.com/128/3097/3097958.png', category: 'luxury' },
        { id: 10, name: '星星', price: '15', image: 'https://cdn-icons-png.flaticon.com/128/1172/1172723.png', category: 'popular' },
        { id: 11, name: '666', price: '66', image: 'https://cdn-icons-png.flaticon.com/128/1022/1022567.png', category: 'popular' },
        { id: 12, name: '啤酒', price: '25', image: 'https://cdn-icons-png.flaticon.com/128/2738/2738730.png', category: 'popular' }
      ]
    }
  },
  
  computed: {
    ...mapState({
      vuex_status_bar_height: state => state.vuex_status_bar_height
    }),
    
    // 获取当前用户ID
    userId() {
      return uni.getStorageSync('userId') || '';
    },
    
    // 获取当前用户头像
    userAvatar() {
      const userInfo = uni.getStorageSync('userInfo');
      return userInfo?.avatar || 'https://picsum.photos/seed/user/100';
    },
    
    // 根据分类过滤礼物
    filteredGifts() {
      if (this.currentGiftCategory === 'all') {
        return this.giftList;
      } else {
        return this.giftList.filter(gift => gift.category === this.currentGiftCategory);
      }
    }
  },
  
  // 页面加载时
  onLoad(options) {
    // 从路由参数获取聊天目标用户信息
    if (options.id) {
      this.targetUser.id = options.id;
      this.targetUser.nickname = options.username || '用户';
      this.targetUser.isOnline = options.isOnline === 'true';
      
      // 获取目标用户详细信息
      this.fetchTargetUserInfo();
    }
    
    // 初始化语音相关功能
    this.initRecorder();
    this.initAudioContext();
    
    // 设置键盘高度监听
    uni.onKeyboardHeightChange((res) => {
      this.keyboardHeight = res.height;
      if (res.height === 0) {
        // 键盘收起时关闭所有面板
        this.resetAllPanels();
      }
    });
  },
  
  // 页面卸载
  onUnload() {
    // 停止播放中的语音
    if (this.innerAudioContext) {
      this.innerAudioContext.stop();
    }
    
    // 解除键盘监听
    uni.offKeyboardHeightChange();
  },
  
  methods: {
    // 加载聊天记录
    async loadMessages(pageNo, pageSize) {
      try {
        // 这里应该是从API加载聊天记录
        // 现在使用模拟数据
        
        if (pageNo === 1) {
          // 模拟第一页数据
          setTimeout(() => {
            const mockMessages = this.generateMockMessages();
            this.$refs.chatPaging.complete(mockMessages);
          }, 500);
        } else {
          // 模拟历史聊天记录
          setTimeout(() => {
            const mockHistoryMessages = this.generateMockHistoryMessages();
            this.$refs.chatPaging.complete(mockHistoryMessages);
          }, 800);
        }
      } catch (error) {
        console.error('加载聊天记录失败:', error);
        this.$refs.chatPaging.complete(false);
      }
    },
    
    // 生成模拟消息数据
    generateMockMessages() {
      const currentTime = Date.now();
      const hourAgo = currentTime - 3600000;
      
      return [
        {
          id: '1',
          type: 'date',
          content: this.formatDate(new Date()),
          timestamp: currentTime
        },
        {
          id: '2',
          type: 'text',
          content: '你好，最近在忙什么呢？',
          senderId: this.targetUser.id,
          timestamp: currentTime - 300000
        },
        {
          id: '3',
          type: 'text',
          content: '我在准备周末的比赛，你要来看吗？',
          senderId: this.userId,
          status: 'read',
          timestamp: currentTime - 240000
        },
        {
          id: '4',
          type: 'image',
          content: 'https://picsum.photos/seed/chat1/500/300',
          senderId: this.targetUser.id,
          timestamp: currentTime - 180000
        },
        {
          id: '5',
          type: 'text',
          content: '这是我们队的新海报，感觉不错吧！',
          senderId: this.targetUser.id,
          timestamp: currentTime - 170000
        },
        {
          id: '6',
          type: 'voice',
          content: 'mock_voice_url',
          duration: '3"',
          senderId: this.userId,
          status: 'read',
          timestamp: currentTime - 120000
        },
        {
          id: '7',
          type: 'text',
          content: '好的，周末见！',
          senderId: this.userId,
          status: 'read',
          timestamp: currentTime - 60000
        },
        {
          id: '8',
          type: 'intimacy',
          content: '亲密度 +1',
          timestamp: currentTime - 30000
        }
      ];
    },
    
    // 生成更多历史消息
    generateMockHistoryMessages() {
      const twoDaysAgo = Date.now() - 172800000;
      
      return [
        {
          id: '101',
          type: 'date',
          content: this.formatDate(new Date(twoDaysAgo)),
          timestamp: twoDaysAgo
        },
        {
          id: '102',
          type: 'text',
          content: '上次的游戏真是太精彩了！',
          senderId: this.targetUser.id,
          timestamp: twoDaysAgo + 3600000
        },
        {
          id: '103',
          type: 'text',
          content: '是啊，特别是最后那个绝杀！',
          senderId: this.userId,
          status: 'read',
          timestamp: twoDaysAgo + 3660000
        },
        {
          id: '104',
          type: 'image',
          content: 'https://picsum.photos/seed/chat2/500/300',
          senderId: this.userId,
          status: 'read',
          timestamp: twoDaysAgo + 3720000
        },
        {
          id: '105',
          type: 'system',
          content: '系统消息：你们已经成为好友，现在可以开始聊天了',
          timestamp: twoDaysAgo + 1800000
        }
      ];
    },
    
    // 获取目标用户详细信息
    async fetchTargetUserInfo() {
      try {
        // 这里应该调用API获取用户信息
        // 现在使用模拟数据
        setTimeout(() => {
          this.targetUser = {
            ...this.targetUser,
            avatar: `https://picsum.photos/seed/user${this.targetUser.id}/100`,
            isOnline: Math.random() > 0.5
          };
        }, 300);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },
    
    // 发送文本消息
    sendTextMessage() {
      if (!this.messageText.trim()) return;
      
      // 创建新消息对象
      const newMessage = {
        id: Date.now().toString(),
        type: 'text',
        content: this.messageText,
        senderId: this.userId,
        status: 'sending',
        timestamp: Date.now()
      };
      
      // 添加到消息列表
      this.messageList.push(newMessage);
      
      // 清空输入框
      this.messageText = '';
      this.resetAllPanels();
      
      // 重置输入框高度
      this.textareaHeight = 20;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.$refs.chatPaging.scrollToBottom();
      });
      
      // 模拟发送过程
      setTimeout(() => {
        const index = this.messageList.findIndex(msg => msg.id === newMessage.id);
        if (index !== -1) {
          this.messageList[index].status = 'sent';
          
          // 再延迟一段时间，模拟已送达
          setTimeout(() => {
            this.messageList[index].status = 'delivered';
            
            // 再延迟一段时间，模拟已读
            setTimeout(() => {
              this.messageList[index].status = 'read';
              
              // 模拟对方回复
              this.simulateReply();
            }, 2000);
          }, 1000);
        }
      }, 500);
    },
    
    // 模拟对方回复
    simulateReply() {
      const replies = [
        '好的，明白了👌',
        '这个主意不错！',
        '什么时候一起开黑？',
        '我最近也在玩这个游戏',
        '周末有空一起打rank吗？'
      ];
      
      const randomReply = replies[Math.floor(Math.random() * replies.length)];
      
      // 模拟对方正在输入
      setTimeout(() => {
        // 添加对方的回复
        const replyMessage = {
          id: Date.now().toString(),
          type: 'text',
          content: randomReply,
          senderId: this.targetUser.id,
          timestamp: Date.now()
        };
        
        this.messageList.push(replyMessage);
        
        // 滚动到底部
        this.$nextTick(() => {
          this.$refs.chatPaging.scrollToBottom();
        });
      }, 1500);
    },
    
    // 选择并发送图片
    async chooseImage(sourceType) {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sourceType: sourceType === 'camera' ? ['camera'] : ['album'],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            
            // 实际应用中，这里应该先上传图片到服务器，获取URL后再发送消息
            // 这里简化处理，直接使用本地临时路径
            
            // 创建新消息对象
            const newMessage = {
              id: Date.now().toString(),
              type: 'image',
              content: tempFilePath, // 实际项目中应该是服务器返回的URL
              senderId: this.userId,
              status: 'sending',
              timestamp: Date.now()
            };
            
            // 添加到消息列表
            this.messageList.push(newMessage);
            
            // 关闭面板
            this.resetAllPanels();
            
            // 滚动到底部
            this.$nextTick(() => {
              this.$refs.chatPaging.scrollToBottom();
            });
            
            // 模拟发送过程
            setTimeout(() => {
              const index = this.messageList.findIndex(msg => msg.id === newMessage.id);
              if (index !== -1) {
                this.messageList[index].status = 'sent';
                
                // 再延迟一段时间，模拟已送达
                setTimeout(() => {
                  this.messageList[index].status = 'delivered';
                  
                  // 再延迟一段时间，模拟已读
                  setTimeout(() => {
                    this.messageList[index].status = 'read';
                  }, 2000);
                }, 1000);
              }
            }, 800);
          }
        });
      } catch (error) {
        console.error('选择图片失败:', error);
      }
    },
    
    // 初始化录音功能
    initRecorder() {
      this.recorderManager = uni.getRecorderManager();
      
      this.recorderManager.onStop((res) => {
        if (this.isRecording) {
          this.isRecording = false;
          
          // 录音结束，发送语音消息
          const newMessage = {
            id: Date.now().toString(),
            type: 'voice',
            content: res.tempFilePath, // 实际项目中应该是服务器返回的URL
            duration: Math.ceil(res.duration / 1000) + '"',
            senderId: this.userId,
            status: 'sending',
            timestamp: Date.now()
          };
          
          // 添加到消息列表
          this.messageList.push(newMessage);
          
          // 关闭面板
          this.resetAllPanels();
          
          // 滚动到底部
          this.$nextTick(() => {
            this.$refs.chatPaging.scrollToBottom();
          });
          
          // 模拟发送过程
          setTimeout(() => {
            const index = this.messageList.findIndex(msg => msg.id === newMessage.id);
            if (index !== -1) {
              this.messageList[index].status = 'sent';
              
              // 再延迟一段时间，模拟已送达
              setTimeout(() => {
                this.messageList[index].status = 'delivered';
                
                // 再延迟一段时间，模拟已读
                setTimeout(() => {
                  this.messageList[index].status = 'read';
                }, 2000);
              }, 1000);
            }
          }, 600);
        }
      });
      
      this.recorderManager.onError((error) => {
        this.isRecording = false;
        console.error('录音失败:', error);
        uni.showToast({
          title: '录音失败',
          icon: 'none'
        });
      });
    },
    
    // 初始化音频播放功能
    initAudioContext() {
      this.innerAudioContext = uni.createInnerAudioContext();
      
      this.innerAudioContext.onEnded(() => {
        this.currentPlayingVoice = -1;
      });
      
      this.innerAudioContext.onError((error) => {
        console.error('音频播放失败:', error);
        uni.showToast({
          title: '音频播放失败',
          icon: 'none'
        });
        this.currentPlayingVoice = -1;
      });
    },
    
    // 开始录音
    startRecording() {
      this.isRecording = true;
      this.recordingTime = 0;
      
      // 开始计时
      this.recordingTimer = setInterval(() => {
        this.recordingTime++;
        
        // 如果超过60秒，自动停止录音
        if (this.recordingTime >= 60) {
          this.stopRecording();
        }
      }, 1000);
      
      // 开始录音
      this.recorderManager.start({
        duration: 60000, // 最长录音时间，单位ms
        sampleRate: 16000, // 采样率
        numberOfChannels: 1, // 录音通道数
        encodeBitRate: 96000, // 编码码率
        format: 'mp3', // 音频格式
        frameSize: 50 // 指定帧大小
      });
      
      // 震动反馈
      uni.vibrateShort({
        success: function() {
          console.log('震动成功');
        }
      });
    },
    
    // 结束录音
    stopRecording() {
      if (this.isRecording) {
        this.isRecording = false;
        
        // 清除计时器
        if (this.recordingTimer) {
          clearInterval(this.recordingTimer);
          this.recordingTimer = null;
        }
        
        this.recorderManager.stop();
        
        // 震动反馈
        uni.vibrateShort();
      }
    },
    
    // 取消录音
    cancelRecording() {
      if (this.isRecording) {
        this.isRecording = false;
        
        // 清除计时器
        if (this.recordingTimer) {
          clearInterval(this.recordingTimer);
          this.recordingTimer = null;
        }
        
        this.recorderManager.stop();
        
        // 震动反馈
        uni.vibrateShort();
        
        uni.showToast({
          title: '已取消录音',
          icon: 'none'
        });
      }
    },
    
    // 播放语音
    playVoice(voiceUrl, index) {
      // 如果正在播放，先停止
      if (this.currentPlayingVoice !== -1) {
        this.innerAudioContext.stop();
        
        // 如果是点击当前正在播放的语音，则停止播放并退出
        if (this.currentPlayingVoice === index) {
          this.currentPlayingVoice = -1;
          return;
        }
      }
      
      // 设置当前播放的语音索引
      this.currentPlayingVoice = index;
      
      // 设置音频来源
      this.innerAudioContext.src = voiceUrl;
      
      // 开始播放
      this.innerAudioContext.play();
    },
    
    // 发送位置信息
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          // 创建新消息对象
          const newMessage = {
            id: Date.now().toString(),
            type: 'text', // 简化处理，实际应该有专门的位置消息类型
            content: `[位置] ${res.name}\n${res.address}`,
            senderId: this.userId,
            status: 'sending',
            timestamp: Date.now()
          };
          
          // 添加到消息列表
          this.messageList.push(newMessage);
          
          // 关闭面板
          this.resetAllPanels();
          
          // 滚动到底部
          this.$nextTick(() => {
            this.$refs.chatPaging.scrollToBottom();
          });
          
          // 模拟发送过程
          setTimeout(() => {
            const index = this.messageList.findIndex(msg => msg.id === newMessage.id);
            if (index !== -1) {
              this.messageList[index].status = 'sent';
              
              // 再延迟一段时间，模拟已送达
              setTimeout(() => {
                this.messageList[index].status = 'delivered';
                
                // 再延迟一段时间，模拟已读
                setTimeout(() => {
                  this.messageList[index].status = 'read';
                }, 2000);
              }, 1000);
            }
          }, 600);
        },
        fail: (error) => {
          console.error('选择位置失败:', error);
        }
      });
    },
    
    // 发送礼物
    sendGift() {
      // 显示礼物弹窗而不是提示
      this.showGiftModal = true;
    },
    
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        current: url,
        urls: [url]
      });
    },
    
    // 查看用户资料
    viewUserProfile(userId) {
      if (userId === this.userId) {
        // 查看自己的资料
        uni.navigateTo({
          url: '/pages/mine/mine'
        });
      } else {
        // 查看对方的资料
        uni.navigateTo({
          url: `/pages/profile/index?userId=${userId}`
        });
      }
    },
    
    // 显示用户信息
    showUserInfo() {
      uni.navigateTo({
        url: `/pages/profile/index?userId=${this.targetUser.id}`
      });
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const today = new Date();
      
      if (
        year === today.getFullYear() &&
        month === (today.getMonth() + 1).toString().padStart(2, '0') &&
        day === today.getDate().toString().padStart(2, '0')
      ) {
        return '今天';
      }
      
      const yesterday = new Date(today);
      yesterday.setDate(today.getDate() - 1);
      
      if (
        year === yesterday.getFullYear() &&
        month === (yesterday.getMonth() + 1).toString().padStart(2, '0') &&
        day === yesterday.getDate().toString().padStart(2, '0')
      ) {
        return '昨天';
      }
      
      return `${year}-${month}-${day}`;
    },
    
    // 调整文本输入框高度
    adjustTextareaHeight(e) {
      const minHeight = 20; // 最小高度
      const maxHeight = 100; // 最大高度
      const lineHeight = 20; // 每行高度
      
      // 计算当前文本行数
      const text = e.detail.value || '';
      const lines = text.split('\n').length;
      const lineBreaks = text.match(/\n/g) || [];
      const actualLines = Math.max(lines, lineBreaks.length + 1);
      
      // 计算新高度
      const newHeight = Math.min(Math.max(actualLines * lineHeight, minHeight), maxHeight);
      this.textareaHeight = newHeight;
    },
    
    // 输入框获取焦点
    onInputFocus() {
      // 设置输入框焦点状态
      this.isInputFocused = true;
      
      // 关闭所有面板
      this.resetAllPanels();
      
      // 延迟滚动到底部
      setTimeout(() => {
        this.$refs.chatPaging.scrollToBottom();
      }, 300);
    },
    
    // 输入框失去焦点
    onInputBlur() {
      // 取消输入框焦点状态
      this.isInputFocused = false;
    },
    
    // 切换表情面板
    toggleEmojiPanel() {
      // 如果表情面板已显示，则隐藏
      if (this.showEmojiPanel) {
        this.showEmojiPanel = false;
        return;
      }
      
      // 如果其他面板显示，则关闭其他面板
      this.showToolPanel = false;
      this.showVoicePanel = false;
      
      // 显示表情面板
      this.showEmojiPanel = true;
      
      // 关闭键盘
      uni.hideKeyboard();
      
      // 延迟滚动到底部
      setTimeout(() => {
        this.$refs.chatPaging.scrollToBottom();
      }, 100);
    },
    
    // 切换工具面板
    toggleToolPanel() {
      // 如果工具面板已显示，则隐藏
      if (this.showToolPanel) {
        this.showToolPanel = false;
        return;
      }
      
      // 如果其他面板显示，则关闭其他面板
      this.showEmojiPanel = false;
      this.showVoicePanel = false;
      
      // 显示工具面板
      this.showToolPanel = true;
      
      // 关闭键盘
      uni.hideKeyboard();
      
      // 延迟滚动到底部
      setTimeout(() => {
        this.$refs.chatPaging.scrollToBottom();
      }, 100);
    },
    
    // 切换语音输入
    toggleVoiceInput() {
      // 如果语音面板已显示，则隐藏
      if (this.showVoicePanel) {
        this.showVoicePanel = false;
        return;
      }
      
      // 如果其他面板显示，则关闭其他面板
      this.showEmojiPanel = false;
      this.showToolPanel = false;
      
      // 显示语音面板
      this.showVoicePanel = true;
      
      // 关闭键盘
      uni.hideKeyboard();
      
      // 延迟滚动到底部
      setTimeout(() => {
        this.$refs.chatPaging.scrollToBottom();
      }, 100);
    },
    
    // 重置所有面板
    resetAllPanels() {
      this.showEmojiPanel = false;
      this.showToolPanel = false;
      this.showVoicePanel = false;
    },
    
    // 表情轮播切换
    onEmojiSwiperChange(e) {
      this.activeEmojiTab = e.detail.current;
    },
    
    // 插入表情
    insertEmoji(emoji) {
      this.messageText += emoji;
    },
    
    // 删除表情/文字
    deleteEmoji() {
      if (this.messageText.length > 0) {
        // 判断最后一个字符是否是emoji表情（通常emoji是由多个字符组成的）
        const lastChar = this.messageText.slice(-2);
        const isEmoji = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g.test(lastChar);
        
        if (isEmoji) {
          // 如果是emoji，则删除两个字符
          this.messageText = this.messageText.slice(0, -2);
        } else {
          // 否则删除一个字符
          this.messageText = this.messageText.slice(0, -1);
        }
      }
    },
    
    // 发送文件
    sendFile() {
      uni.showToast({
        title: '文件发送功能开发中',
        icon: 'none'
      });
      this.resetAllPanels();
    },
    
    // 发起视频通话
    openVideoCall() {
      uni.showToast({
        title: '视频通话功能开发中',
        icon: 'none'
      });
      this.resetAllPanels();
    },
    
    // 发起语音通话
    openVoiceCall() {
      uni.showToast({
        title: '语音通话功能开发中',
        icon: 'none'
      });
      this.resetAllPanels();
    },
    
    // 分享联系人名片
    shareContact() {
      uni.showToast({
        title: '分享名片功能开发中',
        icon: 'none'
      });
      this.resetAllPanels();
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 礼物功能相关方法
    // 关闭礼物弹窗
    closeGiftModal() {
      this.showGiftModal = false;
      this.selectedGift = null;
      this.giftQuantity = 1;
    },
    
    // 切换礼物分类
    changeGiftCategory(categoryId) {
      this.currentGiftCategory = categoryId;
    },
    
    // 选择礼物
    selectGiftItem(gift) {
      this.selectedGift = gift;
    },
    
    // 增加礼物数量
    increaseQuantity() {
      if (this.giftQuantity < 99) {
        this.giftQuantity++;
      }
    },
    
    // 减少礼物数量
    decreaseQuantity() {
      if (this.giftQuantity > 1) {
        this.giftQuantity--;
      }
    },
    
    // 计算礼物总价
    calculateTotalPrice() {
      if (!this.selectedGift) return 0;
      return parseInt(this.selectedGift.price) * this.giftQuantity;
    },
    
    // 赠送选中的礼物
    sendSelectedGift() {
      if (!this.selectedGift) return;
      
      // 检查余额是否足够
      const totalPrice = this.calculateTotalPrice();
      if (totalPrice > this.userBalance) {
        uni.showModal({
          title: '余额不足',
          content: '您的余额不足，是否立即充值？',
          confirmText: '去充值',
          success: (res) => {
            if (res.confirm) {
              // 跳转到充值页面
              this.rechargeBalance();
            }
          }
        });
        return;
      }
      
      // 创建礼物消息
      const newMessage = {
        id: Date.now().toString(),
        type: 'gift',
        content: JSON.stringify({
          giftId: this.selectedGift.id,
          giftName: this.selectedGift.name,
          giftImage: this.selectedGift.image,
          quantity: this.giftQuantity,
          price: this.selectedGift.price
        }),
        senderId: this.userId,
        status: 'sending',
        timestamp: Date.now()
      };
      
      // 添加到消息列表
      this.messageList.push(newMessage);
      
      // 关闭礼物弹窗
      this.closeGiftModal();
      
      // 扣除用户余额
      this.userBalance -= totalPrice;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.$refs.chatPaging.scrollToBottom();
      });
      
      // 模拟发送过程
      setTimeout(() => {
        const index = this.messageList.findIndex(msg => msg.id === newMessage.id);
        if (index !== -1) {
          this.messageList[index].status = 'sent';
          
          // 模拟送达和已读
          setTimeout(() => {
            this.messageList[index].status = 'delivered';
            setTimeout(() => {
              this.messageList[index].status = 'read';
              
              // 模拟亲密度变化
              this.checkIntimacyLevelUp(totalPrice);
            }, 1000);
          }, 1000);
        }
      }, 600);
    },
    
    // 前往充值
    rechargeBalance() {
      uni.navigateTo({
        url: '/pages/wallet/recharge'
      });
    },
    
    // 检查亲密度等级提升
    checkIntimacyLevelUp(addValue) {
      // 计算新的亲密度
      const newIntimacyValue = this.intimacyValue + Math.floor(addValue / 10);
      const newIntimacyLevel = Math.floor(newIntimacyValue / this.maxIntimacyValue) + 1;
      
      // 如果等级提升，则添加一条系统消息
      if (newIntimacyLevel > this.intimacyLevel) {
        const levelUpMessage = {
          id: Date.now().toString() + '-system',
          type: 'intimacy',
          content: `恭喜！你们的亲密度提升到了 Lv.${newIntimacyLevel}`,
          timestamp: Date.now()
        };
        
        this.messageList.push(levelUpMessage);
        
        // 滚动到底部
        this.$nextTick(() => {
          this.$refs.chatPaging.scrollToBottom();
        });
        
        // 显示亲密度升级弹窗
        setTimeout(() => {
          this.showIntimacyLevelUpModal();
        }, 800);
      }
      
      // 更新亲密度值和等级
      this.intimacyValue = newIntimacyValue;
      this.intimacyLevel = newIntimacyLevel;
    },
    
    // 显示亲密度升级弹窗
    showIntimacyLevelUpModal() {
      this.showLevelUpModal = true;
    },
    
    // 关闭亲密度升级弹窗
    closeIntimacyLevelUpModal() {
      this.showLevelUpModal = false;
    },
    
    // 解析礼物消息内容
    parseGiftContent(content) {
      try {
        return JSON.parse(content);
      } catch (e) {
        console.error('解析礼物内容失败:', e);
        return { giftId: 0, giftName: '未知礼物', giftImage: '', quantity: 1, price: 0 };
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-page {
  background-color: #020303;
  min-height: 100vh;
  position: relative;
}

/* 头部样式 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: rgba(18, 18, 18, 0.95);
  backdrop-filter: blur(10px);
  transition: background-color 0.3s ease;
  border-bottom: 1px solid #2a2a2a;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-btn {
  background: none;
  border: none;
  color: #e0e0e0;
  cursor: pointer;
  padding: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s ease;
  border-radius: 50%;
  width: 36px;
  height: 36px;
}

.back-btn:active {
  transform: scale(0.9);
  background-color: rgba(255, 255, 255, 0.1);
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  text-align: center;
  margin: 0 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.username {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.online-status {
  font-size: 12px;
  color: #B3F73C;
  margin-top: 2px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.icon-btn {
  background: none;
  border: none;
  color: #e0e0e0;
  cursor: pointer;
  padding: 6px;
  transition: transform 0.2s ease;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-btn:active {
  transform: scale(0.9);
  background-color: rgba(255, 255, 255, 0.1);
}

/* 聊天内容区域 */
.chat-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
  animation: fadeIn 0.3s;
  position: relative;
  margin-bottom: 16px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(15px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.sent {
  align-self: flex-end;
  flex-direction: row-reverse;
  padding-right: 6px;
}

.message.received {
  align-self: flex-start;
  padding-left: 6px;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 2px solid rgba(108, 92, 231, 0.1);
  transition: transform 0.2s ease;
  flex-shrink: 0;
}

.message-avatar:active {
  transform: scale(1.1);
}

.message-avatar image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  background-color: #2a2a2a;
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
  transition: all 0.2s ease;
  max-width: 100%;
}

.message-content:active {
  transform: scale(0.98);
  filter: brightness(1.05);
}

.message.sent .message-content {
  background: linear-gradient(135deg, #6c5ce7, #574bd6);
  border-bottom-right-radius: 4px;
}

.message.sent .message-content::before {
  content: '';
  position: absolute;
  bottom: 0;
  right: -8px;
  width: 16px;
  height: 16px;
  background: linear-gradient(225deg, #574bd6, transparent);
  border-bottom-left-radius: 16px;
  z-index: -1;
}

.message.received .message-content {
  background-color: rgba(42, 42, 42, 0.9);
  backdrop-filter: blur(10px);
  border-bottom-left-radius: 4px;
  border-left: 1px solid rgba(255, 255, 255, 0.1);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.message.received .message-content::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: -8px;
  width: 16px;
  height: 16px;
  background: rgba(42, 42, 42, 0.9);
  border-bottom-right-radius: 16px;
  z-index: -1;
}

/* 系统消息样式 */
.message.system {
  align-self: center;
  max-width: 90%;
  margin-bottom: 12px;
}

.message.system .message-content {
  background-color: rgba(55, 55, 55, 0.6);
  border-radius: 12px;
  padding: 6px 12px;
  text-align: center;
  display: inline-block;
  backdrop-filter: blur(5px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.message-intimacy {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.intimacy-icon {
  color: #B3F73C;
}

/* 消息状态指示器 */
.message-status {
  position: absolute;
  right: -18px;
  bottom: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background-color: #1a1a1a;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  z-index: 5;
  padding: 1px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.message.received .message-status {
  left: -18px;
  right: auto;
}

.status-sending {
  color: #e0e0e0;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.status-sent {
  color: #e0e0e0;
}

.status-delivered {
  color: #a29bfe;
}

.status-read {
  color: #6c5ce7;
}

.status-failed {
  color: #ff5252;
}

.message-text {
  font-size: 15px;
  line-height: 1.5;
  margin-bottom: 4px;
  word-break: break-word;
  font-weight: 400;
}

.message.sent .message-text {
  color: rgba(255, 255, 255, 0.95);
}

.message-time {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.5);
  text-align: right;
  margin-top: 4px;
}

.message.received .message-time {
  color: rgba(255, 255, 255, 0.4);
}

.message-image {
  margin: -8px -12px;
  overflow: hidden;
  border-radius: 14px;
}

.message-image image {
  max-width: 240px;
  width: 100%;
  border-radius: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: block;
}

.message-image image:active {
  transform: scale(0.98);
  filter: brightness(1.05);
}

.message-voice {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 140px;
  padding: 6px 2px;
  position: relative;
  cursor: pointer;
}

.voice-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #e0e0e0;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  padding: 6px;
}

.message.received .voice-icon {
  background: rgba(0, 0, 0, 0.1);
}

.message.sent .voice-icon {
  color: rgba(255, 255, 255, 0.9);
  background: rgba(255, 255, 255, 0.2);
}

.voice-wave {
  display: flex;
  align-items: center;
  gap: 2px;
  height: 20px;
  width: 40px;
}

.wave-bar {
  flex: 1;
  height: 5px;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 3px;
}

.message.received .wave-bar {
  background-color: rgba(255, 255, 255, 0.3);
}

.message-voice.playing .wave-bar {
  animation: voiceWave 1.5s ease-in-out infinite;
}

.message-voice.playing .wave-bar:nth-child(1) { animation-delay: 0.1s; }
.message-voice.playing .wave-bar:nth-child(2) { animation-delay: 0.3s; }
.message-voice.playing .wave-bar:nth-child(3) { animation-delay: 0.5s; }
.message-voice.playing .wave-bar:nth-child(4) { animation-delay: 0.2s; }
.message-voice.playing .wave-bar:nth-child(5) { animation-delay: 0.4s; }

@keyframes voiceWave {
  0%, 100% { height: 5px; }
  50% { height: 15px; }
}

.voice-duration {
  font-size: 14px;
  color: #a0a0a0;
  font-weight: 500;
}

/* 输入栏样式 */
.input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #1a1a1a;
  border-top: 1px solid #2a2a2a;
  transition: transform 0.3s ease, bottom 0.3s ease;
  z-index: 10;
}

.input-container {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  gap: 10px;
}

.input-box {
  flex: 1;
  background-color: #2a2a2a;
  border-radius: 20px;
  padding: 8px 15px;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.input-box-focused {
  border-color: #6c5ce7;
  box-shadow: 0 0 0 2px rgba(108, 92, 231, 0.2);
}

.message-input {
  width: 100%;
  background: transparent;
  color: #ffffff;
  font-size: 14px;
  line-height: 1.4;
  min-height: 20px;
  max-height: 100px;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #e0e0e0;
  font-size: 20px;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.action-btn.active {
  color: #B3F73C;
  background-color: rgba(179, 247, 60, 0.1);
}

.action-btn:active {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(0.9);
}

.send-btn {
  background-color: #6c5ce7;
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  padding: 8px 15px;
  border-radius: 18px;
  transition: all 0.2s ease;
}

.send-btn:active {
  transform: scale(0.95);
  background-color: #574bd6;
}

/* 语音输入面板 */
.voice-panel {
  background-color: #1a1a1a;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 160px;
  transition: all 0.3s ease;
}

.voice-button {
  background-color: #2a2a2a;
  padding: 15px 40px;
  border-radius: 50px;
  color: #ffffff;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.2s ease;
  position: relative;
}

.voice-button.recording {
  background-color: #6c5ce7;
  border-color: #574bd6;
  transform: scale(1.05);
}

.voice-button:active {
  background-color: #3a3a3a;
  transform: scale(0.98);
}

.recording-waves {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  border-radius: 50px;
  pointer-events: none;
}

.wave-circle {
  position: absolute;
  border: 2px solid #B3F73C;
  border-radius: 50px;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
  animation: wave 2s infinite;
}

.wave-circle:nth-child(2) {
  animation-delay: 0.5s;
}

.wave-circle:nth-child(3) {
  animation-delay: 1s;
}

@keyframes wave {
  0% {
    transform: scale(1);
    opacity: 0.7;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

.recording-tip {
  margin-top: 15px;
  color: #a0a0a0;
  font-size: 12px;
}

/* 工具面板 */
.tool-panel {
  background-color: #1a1a1a;
  padding: 20px 15px 30px;
  transition: all 0.3s ease;
  max-height: 260px;
  overflow-y: auto;
}

.tool-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px 10px;
}

.tool-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.tool-icon {
  width: 50px;
  height: 50px;
  background-color: #2a2a2a;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #e0e0e0;
  transition: all 0.2s ease;
}

.tool-icon:active {
  transform: scale(0.9);
  background-color: #3a3a3a;
}

.tool-name {
  font-size: 12px;
  color: #a0a0a0;
}

/* 表情面板 */
.emoji-panel {
  background-color: #1a1a1a;
  transition: all 0.3s ease;
  height: 260px;
  display: flex;
  flex-direction: column;
}

.emoji-tabs {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #2a2a2a;
  position: relative;
}

.emoji-tabs-scroll {
  flex: 1;
  white-space: nowrap;
  overflow-x: auto;
}

.emoji-tab {
  display: inline-block;
  padding: 6px 15px;
  color: #a0a0a0;
  font-size: 14px;
  margin-right: 10px;
  border-radius: 15px;
  transition: all 0.2s ease;
}

.emoji-tab.active {
  background-color: #2a2a2a;
  color: #ffffff;
}

.emoji-delete {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #e0e0e0;
  font-size: 20px;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.emoji-delete:active {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(0.9);
}

.emoji-content {
  flex: 1;
  height: 100%;
}

.emoji-list {
  height: 100%;
  padding: 10px;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
  padding: 5px;
}

.emoji-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  font-size: 24px;
  transition: all 0.2s ease;
}

.emoji-item:active {
  transform: scale(1.2);
}

.emoji-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  border-top: 1px solid #2a2a2a;
}

.emoji-send-btn {
  background-color: #6c5ce7;
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  padding: 8px 15px;
  border-radius: 18px;
  transition: all 0.2s ease;
}

.emoji-send-btn:active {
  transform: scale(0.95);
  background-color: #574bd6;
}

/* 礼物弹窗样式 */
.gift-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  animation: fadeIn 0.3s;
  backdrop-filter: blur(5px);
}

.gift-modal-content {
  width: 100%;
  background-color: #1a1a1a;
  border-radius: 24px 24px 0 0;
  padding: 20px;
  animation: slideUp 0.3s;
}

.gift-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.gift-modal-title {
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(90deg, #B3F73C, #00C4FF);
  -webkit-background-clip: text;
  color: transparent;
}

.gift-modal-close {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 15px;
  background-color: #2a2a2a;
}

.gift-modal-user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #2a2a2a;
  padding: 12px 15px;
  border-radius: 12px;
  margin-bottom: 15px;
}

.gift-modal-balance {
  display: flex;
  align-items: center;
  color: #e0e0e0;
  font-size: 14px;
}

.balance-amount {
  color: #F1C40F;
  margin-left: 5px;
  font-weight: 500;
}

.recharge-btn {
  background: linear-gradient(90deg, #B3F73C, #00C4FF);
  color: #020303;
  font-weight: 500;
  padding: 6px 15px;
  border-radius: 20px;
  font-size: 14px;
}

.gift-categories {
  margin-bottom: 15px;
}

.gift-category-scroll {
  white-space: nowrap;
  width: 100%;
}

.gift-category-btn {
  display: inline-block;
  padding: 8px 15px;
  margin-right: 10px;
  background-color: #2a2a2a;
  border-radius: 20px;
  font-size: 14px;
  transition: all 0.3s;
}

.gift-category-btn.active {
  background: linear-gradient(90deg, #B3F73C, #00C4FF);
  color: #020303;
  font-weight: 500;
}

.gift-grid-container {
  margin-bottom: 15px;
}

.gift-grid {
  height: 200px;
}

.gift-grid-items {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  padding: 5px;
}

.gift-item {
  background-color: #2a2a2a;
  border-radius: 12px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s;
}

.gift-item.selected {
  background-color: #3a3a3a;
  box-shadow: 0 0 0 2px #B3F73C;
}

.gift-image {
  width: 45px;
  height: 45px;
  margin-bottom: 5px;
}

.gift-name {
  font-size: 12px;
  margin-bottom: 3px;
  text-align: center;
}

.gift-price {
  font-size: 12px;
  color: #F1C40F;
  display: flex;
  align-items: center;
}

.gift-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.gift-quantity {
  display: flex;
  align-items: center;
}

.quantity-label {
  font-size: 14px;
  margin-right: 5px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  background-color: #2a2a2a;
  border-radius: 20px;
  padding: 2px;
}

.quantity-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
}

.quantity-value {
  width: 30px;
  text-align: center;
}

.total-price {
  font-size: 14px;
  display: flex;
  align-items: center;
  color: #F1C40F;
}

.send-gift-btn {
  background: linear-gradient(90deg, #B3F73C, #00C4FF);
  color: #020303;
  font-weight: 500;
  padding: 6px 20px;
  border-radius: 20px;
  font-size: 14px;
}

/* 礼物消息样式 */
.message-gift {
  background-color: rgba(179, 247, 60, 0.1);
  border-radius: 12px;
  margin-bottom: 3px;
  overflow: hidden;
  border: 1px solid rgba(179, 247, 60, 0.3);
}

.gift-content {
  padding: 10px;
}

.gift-title {
  font-size: 12px;
  color: #B3F73C;
  margin-bottom: 5px;
}

.gift-detail {
  display: flex;
  align-items: center;
}

.gift-left {
  margin-right: 10px;
}

.gift-thumbnail {
  width: 40px;
  height: 40px;
  background-color: #2a2a2a;
  border-radius: 8px;
}

.gift-right {
  flex: 1;
}

.gift-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
}

.gift-quantity {
  font-size: 12px;
  color: rgba(224, 224, 224, 0.7);
}

/* 亲密度升级弹窗样式 */
.intimacy-levelup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: fadeIn 0.3s;
  backdrop-filter: blur(5px);
}

.levelup-content {
  width: 80%;
  background-color: #1a1a1a;
  border-radius: 20px;
  padding: 20px;
  text-align: center;
  animation: zoomIn 0.3s;
}

.levelup-icon {
  font-size: 40px;
  margin-bottom: 15px;
  color: #B3F73C;
}

.levelup-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  background: linear-gradient(90deg, #B3F73C, #00C4FF);
  -webkit-background-clip: text;
  color: transparent;
}

.levelup-desc {
  font-size: 14px;
  margin-bottom: 20px;
  color: #e0e0e0;
}

.levelup-progress {
  font-size: 12px;
  color: rgba(224, 224, 224, 0.7);
  margin-top: 8px;
}

.levelup-btn {
  background: linear-gradient(90deg, #B3F73C, #00C4FF);
  color: #020303;
  font-weight: 500;
  padding: 10px 30px;
  border-radius: 20px;
  font-size: 16px;
  display: inline-block;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}

@keyframes zoomIn {
  from { transform: scale(0.8); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
</style> 